<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="车位编号">
              <el-input v-model="formInline.code"></el-input>
            </el-form-item>
            <el-form-item label="停车场编号">
              <el-input v-model="formInline.lotCode"></el-input>
            </el-form-item>
            <el-form-item label="是否可用">
              <el-select v-model="formInline.isAvailable" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预定用户ID">
              <el-input v-model="formInline.userId"></el-input>
            </el-form-item>
            <el-form-item label="是否会员专属">
              <el-select v-model="formInline.isMemberOnly" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="是" :value="1"></el-option>
                <el-option label="否" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button type="info" @click="resetQueryData">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-loading="isLoading" element-loading-text="加载中...">
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70" align="center" style = "background-color :black">
              <template #default="scope">
                <div class="serial-number">
                  {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="车位id" v-if="false"></el-table-column>
            <el-table-column prop="code" label="车位编号" width="120"></el-table-column>
            <el-table-column prop="lotCode" label="停车场编号" width="120"></el-table-column>
            <el-table-column prop="name" label="停车场名称" width="120"></el-table-column>
            <el-table-column prop="address" label="停车场地址" width="200"></el-table-column>
            <el-table-column prop="operatingHours" label="营业时间" width="180"></el-table-column>
            <el-table-column prop="phone" label="联系电话" width="100"></el-table-column>
            <el-table-column prop="feeScheduleCode" label="收费策略编号"  v-if="false"></el-table-column>
            <el-table-column prop="hourlyRate" label="每小时费率(元/时)" width="100"></el-table-column>
            <el-table-column prop="description" label="停车场描述" width="220"></el-table-column>
            <el-table-column prop="isAvailable" label="是否可用" width="120">
              <template #default="scope">
                <span>{{ scope.row.isAvailable === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isMemberOnly" label="是否会员专属" width="120">
              <template #default="scope">
                <span>{{ scope.row.isMemberOnly === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userId" label="预定用户ID" width="120"></el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button 
                  size="success" 
                  :disabled="scope.row.isAvailable !== 1" 
                  @click="handleInsert(scope.row)"
                >
                  预定
                </el-button>
              </template>
              
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
            <el-config-provider :locale="locale">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              ></el-pagination>
            </el-config-provider>
          </div>
        </el-card>
        <el-card v-loading="isLoading" element-loading-text="加载中...">
          <template #header>
              <div>
              <h3>预定记录</h3>
              </div>
          </template>
          <el-table :data="reservationTableData" border style="width: 100%" @selection-change="handleSelectionChange2">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="70" align="center" style = "background-color :black">
              <template #default="scope">
                <div class="serial-number">
                  {{ (currentPage2 - 1) * pageSize2 + scope.$index + 1 }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="id" label="入场记录id" v-if="false"></el-table-column>
            <el-table-column prop="lotCode" label="停车场编号" width="180"></el-table-column>
            <el-table-column prop="spaceCode" label="车位编号" width="180"></el-table-column>
            <el-table-column prop="status" label="预定状态"></el-table-column>
            <el-table-column prop="startTime" label="预定起始时间"></el-table-column>
            <el-table-column prop="endTime" label="预定结束时间"></el-table-column>
            <el-table-column prop="userId" label="用户ID" v-if="false"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button 
                  size="danger" 
                  :disabled="scope.row.status !== '已预订'" 
                  @click="handleCancel(scope.row)"
                >
                  取消预定
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px; margin-bottom: 20px; text-align: right; float: right;">
            <el-config-provider :locale="locale">
              <el-pagination
                background
                layout="total2, sizes, prev, pager, next, jumper"
                :total="total2"
                :current-page="currentPage2"
                :page-size="pageSize2"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange2"
                @current-change="handleCurrentChange2"
              ></el-pagination>
            </el-config-provider>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn'; 
import { ref, watch } from 'vue';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';

const route = useRoute();

const formInline = ref({
  id: '',
  lotCode: '',
  isAvailable: '',
  userId: '',
  isMemberOnly: '',
  code: ''
});
const tableData = ref([]);
const reservationTableData = ref([]);
const total = ref(0);
const total2 = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const currentPage2 = ref(1);
const pageSize2 = ref(10);
const locale = zhCn;
const isLoading = ref(false);
const selectedIds = ref([]);
const selectedIds2 = ref([]);

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})
// 监听路由变化, 避免在其他页面修改影响本页面数据时不自动刷新的情况
watch(() => route.path, (newPath) => {
  if(newPath === '/user/ReservationManagement') {
    console.error("刷新ReservationManagement");
    fetchData();
  }
});
const fetchData = async () => {
  isLoading.value = true;
  const params = {
    ...formInline.value,
    pageIndex: currentPage.value,
    pageSize: pageSize.value
  };
  Object.keys(params).forEach(key => (params[key] === '' || params[key] === null) && delete params[key]);
  try {
    const response = await api.get('/api/v1/parking-space/parking-space-info', { params });
    if (response.data.code === "200") {
      if(response.data.data != null){
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          tableData.value = [];
          total.value = 0;
        }
      // 遍历tableData中的每一项，获取并更新停车场和收费策略信息
      for (let i = 0; i < tableData.value.length; i++) {
        const parkingSpace = tableData.value[i];
        // 查询停车场信息
        const parkingLotResponse = await api.get('/api/v1/parking-lot/parking-lot-info', {
          params: { lotCode: parkingSpace.lotCode }
        });
        if(parkingLotResponse.data.code === "200" && parkingLotResponse.data.data) {
          const parkingLotInfo = parkingLotResponse.data.data.records[0];
          // 更新停车位记录中的停车场信息
          tableData.value[i].name = parkingLotInfo.name;
          tableData.value[i].address = parkingLotInfo.address;
          tableData.value[i].operatingHours = parkingLotInfo.operatingHours;
          tableData.value[i].phone = parkingLotInfo.phone;
          tableData.value[i].feeScheduleCode = parkingLotInfo.feeScheduleCode;
          tableData.value[i].description = parkingLotInfo.description;
          // 查询收费策略信息
          const feeScheduleResponse = await api.get('/api/v1/fee-schedule/fee-schedule-info', {
            params: { feeScheduleCode: parkingLotInfo.feeScheduleCode }
          });
          if(feeScheduleResponse.data.code === "200" && feeScheduleResponse.data.data) {
            const feeScheduleInfo = feeScheduleResponse.data.data.records[0];
            tableData.value[i].hourlyRate = feeScheduleInfo.hourlyRate;
          }
        }
      }
    } else {
      ElMessage({
        title: '错误',
        message: '获取停车位记录失败！' + response.data.message,
        type: 'error',
        showClose: false
      });
    }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取停车位记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
    fetchData2();
  }
};

const fetchData2 = async () => {
  isLoading.value = true;
  const params = {
      userId: localStorage.getItem("id"),
      page: currentPage2.value,
      pageSize: pageSize2.value
    };
  try {
    const response = await api.get('/api/v1/reservation/reservation-info', { params });
      if (response.data.code === "200") {
        if(response.data.data != null){
          reservationTableData.value = response.data.data.records;
          total2.value = response.data.total;
        } else {
          reservationTableData.value = [];
          total2.value = 0;
        }
      } else {
        ElMessage({
          title: '错误',
          message: '获取预定记录失败！' + response.data.message,
          type: 'error',
          showClose: false
        });
      }
  } catch (error) {
    ElMessage({
      title: '错误',
      message: '获取预定记录失败！' + error.message,
      type: 'error',
      showClose: false
    });
  } finally {
    isLoading.value = false;
  }
};

const handleInsert = async (row) => {
  if (row.isMemberOnly === 1 && localStorage.getItem("role") !== "会员") {
    ElMessage({
      title: '错误',
      message: '预定失败！该车位为会员专享',
      type: 'error',
    });
    return;
  }
  try {
    await ElMessageBox.confirm(
      `<div>预定仅保留两小时，请遵守时间`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      }
    );

    const reserveResponse = await api.post('/api/v1/reservation/reserve', {
      userId: localStorage.getItem("id"),
      spaceCode: row.code,
      lotCode: row.lotCode
    });
    if (reserveResponse.data.code !== "200") {
      throw new Error(reserveResponse.data.message || '预定记录新增失败');
    }

    console.error(localStorage.getItem("id"));
    const updateResponse = await api.put('/api/v1/parking-space/parking-space-info', {
      id: row.id,
      isAvailable: 0,
      userId: localStorage.getItem("id")
    });
    if (updateResponse.data.code !== "200") {
      throw new Error(updateResponse.data.message || '车位状态更新失败');
    }

    await fetchData();
    ElMessage({
      title: '成功',
      message: '预定记录新增成功',
      type: 'success',
      showClose: false,
    });

  } catch (error) {
    if (error === 'cancel') {
      ElMessage({
        type: 'info',
        message: '已取消预定',
      });
    } else {
      ElMessage({
        title: '错误',
        message: `操作失败！${error.message}`,
        type: 'error',
      });
    }
  }
};

const handleCancel = async (row) => {
  try {
    // 根据lotCode和spaceCode查找唯一记录
    const spaceResponse = await api.get('/api/v1/parking-space/parking-space-info-precise', {
      params: {
        lotCode: row.lotCode,
        spaceCode: row.spaceCode
      }
    });
    if (spaceResponse.data.code !== "200" || !spaceResponse.data.data) {
      throw new Error('未找到对应的车位记录');
    }
    const parkingSpaceRecord = spaceResponse.data.data;
    const updateSpaceResponse = await api.put('/api/v1/parking-space/parking-space-info', {
      id: parkingSpaceRecord.id,
      isAvailable: 1,
      userId: ""
    });
    if (updateSpaceResponse.data.code !== "200") {
      throw new Error('车位状态更新失败');
    }

    // 发送请求删除预定记录([scope.row.id])
    const leaveResponse = await api.delete('/api/v1/reservation/reservation-info', {
      data: { ids: [row.id]}
    });

    if (leaveResponse.data.code === "200") {
      await fetchData(); // 刷新页面数据
      ElMessage({
        message: '预定取消成功',
        type: 'success'
      });
    } else {
      throw new Error('预定记录更新失败：' + leaveResponse.data.message);
    }

  } catch (error) {
    // 如果用户点击了取消按钮，error 将是 'cancel'
    if (error !== 'cancel') {
      ElMessage({
        message: '预定取消失败！' + error.message,
        type: 'error'
      });
    } else {
      ElMessage({
        type: 'info',
        message: '预定取消失败'
      });
    }
  }
};

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};
const handleSelectionChange2 = (selection) => {
  selectedIds2.value = selection.map(item => item.id);
};
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};
const handleCurrentChange2 = (page) => {
  currentPage2.value = page;
  fetchData2();
};
const handleSizeChange2 = (size) => {
  pageSize2.value = size;
  fetchData2();
};

const resetQueryData = () =>{
  formInline.value = {
    id: '',
    lotCode: '',
    isAvailable: '',
    userId: '',
    isMemberOnly: '',
    code: ''
  };
  fetchData();
}

// 页面加载时自动获取数据
fetchData();
</script>

<style scoped>
.admin-dashboard {
  height: 100vh;
}
.el-container {
  height: 100%;
}
.el-aside {
  background-color: #f8f9fa;
}
.el-main {
  padding: 20px;
}
.el-card {
  margin-bottom: 20px; /* 卡片底部外边距 */
}
/* 确保鼠标悬停时的交互效果不变 */
.el-table .cell {
  pointer-events: none; /* 禁用单元格内的点击事件以保留默认的行选中效果 */
}
.el-select {
  width: 180px; /* 设置你希望的宽度 */
}
</style>